from django.shortcuts import render
import logging
# Create your views here.
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.settings import api_settings
from oauth.exception import AboutQQexception
from oauth.models import OAuthQQUser
from oauth.serializers import OAuthQQUserSerializer
from oauth.utils import OAuthQQ
logger=logging.getLogger('django')

class QQAuthURLView(APIView):
    # GET /oauth/qq/authorization/?status=xxxxxx
    def get(self,request):
        status=request.query_params.get('status')
        if not status:
            status='/'
        oauth=OAuthQQ()
        auth_url=oauth.get_auth_url()
        return Response({'auth_url':auth_url})


# GET /oauth/qq/user/?code=xxx
class QQAuthUserView(GenericAPIView):

    def get(self,request):
        # 接收code
        code=request.query_params.get('code')
        # 服务器向qq服务器请求access_token
        oauth = OAuthQQ()
        try:
            access_token=oauth.get_access_token(code)
            # 通accesstoken向ｑｑ服务器要openid
            openid=oauth.get_openid(access_token)
        except AboutQQexception:
            return Response({'message': 'QQ服务异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
        # 通过openid查询数据库有没有这个用户
        try:
            print(OAuthQQUser.objects.get(openid=openid))
            oauth_user=OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 如果没有这人
            access_token=oauth.generate_save_user_token(openid)
            return Response({'access_token': access_token})

        else:
            user=oauth_user.user
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            response={       'token':token,
                             'username':user.username,
                             'user_id':user.id}
            return Response(response)

    serializer_class = OAuthQQUserSerializer
    def post(self,request):
        serializer=self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user=serializer.save()
        # 生成已登录的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        response = {'token': token,
                    'username': user.username,
                    'user_id': user.id}
        return Response(response)
